package com.cysion.study.ui.personal

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.View
import com.cysion.other.color
import com.cysion.study.R
import com.cysion.study.adapter.ClassDetailAdapter
import com.cysion.study.adapter.ClassDetailAdapter.Companion.agree
import com.cysion.study.adapter.ClassDetailAdapter.Companion.preview
import com.cysion.study.adapter.ClassDetailAdapter.Companion.refuse
import com.cysion.study.entity.Studentlist
import com.cysion.study.helper.UserCache
import com.cysion.study.ktbox.Box.context
import com.cysion.study.ktbox.base.BaseActivity
import com.cysion.study.ktbox.net.BaseResponseRx
import com.cysion.study.ktbox.net.ErrorHandler
import com.cysion.study.ktbox.utils.CLog
import com.cysion.study.ktbox.utils.darkTextTheme
import com.cysion.study.net.ApiClient
import com.cysion.study.ui.AddKnowActivity
import com.cysion.study.uibox.bar.TopBar
import com.cysion.study.uibox.dialog.Alert
import com.cysion.study.widget.ShowToast
import com.cysion.study.widget.UIHelper
import com.cysion.targetfun._subscribe
import com.scwang.smartrefresh.layout.constant.RefreshState
import kotlinx.android.synthetic.main.activity_class_detail.*

//课程列表的课列表详情
class ClassDetailActivity : BaseActivity(), View.OnClickListener {


    //    private var mdatalist: MutableList<String> = mutableListOf()
    private lateinit var pendingAdapter: ClassDetailAdapter
    private var curPage = 1
    override fun getLayoutId(): Int = R.layout.activity_class_detail

    private var courseId = ""
    override fun initView() {
        courseId = intent.extras.getString("courseId")
        darkTextTheme(color(R.color.white))
        topbar.apply {
            setTitleBackColor(color(R.color.white))
            setTitle("课程详情")
            setOnTopBarClickListener { obj, pos ->
                if (pos == TopBar.Pos.LEFT) {
                    finish()
                }
            }
        }
        initRefreshLayout()
        initRecyclerView()
        tv_know.setOnClickListener(this)
        tv_address.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_know -> {
                /*var bundle=Bundle()
                bundle.putString("courseId", courseId)
                UIHelper.jump(self, KnowListActivity::class.java,bundle)//习题与知识点*/

                var bundle = Bundle()
                bundle.putString("courseId", courseId)
                bundle.putString("className", className)
                bundle.putString("classTime", classTime)
                UIHelper.jump(self, AddKnowActivity::class.java, bundle)//添加习题与知识
            }
            R.id.tv_address->{
                if (TextUtils.isEmpty(latitude) || latitude == "0") {
                    ShowToast( "未添加位置信息")
                    return
                }
//            var latLng = LatLng(latitude.toDouble(), longitude.toDouble())
                UIHelper.goToBaidu(this,latitude,longitude,address)
            }
        }
    }

    override fun initData() {
        super.initData()
        smartLayout.autoRefresh()
//        smartLayout.finishRefresh()
    }

    //    初始化刷新控件
    private fun initRefreshLayout() {
//        smartLayout.setEnableLoadMore(false)
        smartLayout.setOnRefreshListener {
            getDataList()
            smartLayout.setEnableLoadMore(true)
        }
        smartLayout.setOnLoadMoreListener {

            getDataList()
        }

        //模拟数据
        /* if (classAdapter.itemCount == 0) {
             var lists: MutableList<String> = mutableListOf("","")
             mSourceList.addAll(lists)
             classAdapter.notifyDataSetChanged()
         }*/
    }

    //初始化列表
    private fun initRecyclerView() {
        rv_list.isNestedScrollingEnabled = false
        pendingAdapter = ClassDetailAdapter(dataList, context)
        rv_list.adapter = pendingAdapter
        rv_list.layoutManager = LinearLayoutManager(context)
        pendingAdapter.setOnTypeClickListener { obj, position, flag ->
            /* if (flag == ITEM_CLICK) {//研学详情
                 var bundle = Bundle()
                 bundle.putString("type","1")//type 1 职位入口进详情 2 我的应聘入口进详情
                 startActivity_ex<StudiesDetailActivity>("key", bundle)
             }*/
            if (flag == preview) {//提交点评
//                ShowToast("点评")
                var bundle = Bundle()
                bundle.putString("courseId", courseId)//课程id
                bundle.putString("stuid", obj.sid)//stuid学生id
                bundle.putString("type","1")//1提交点评、2编辑
                UIHelper.jumpForResult(this, CommentActivity::class.java, bundle,301)
            } else if (flag == refuse) {
//                ShowToast("查看点评")
                if (TextUtils.isEmpty(obj.depositid)) {
                    ShowToast("点评id未返回")
                    return@setOnTypeClickListener
                }
                var bundle = Bundle()
                bundle.putString("courseId", courseId)//课程id
                bundle.putString("stuid", obj.sid)//stuid学生id
                bundle.putString("depositid", obj.depositid)//
                UIHelper.jump(this, CommentDetailActivity::class.java, bundle)

            } else if (flag == agree) {
//                ShowToast("签到")
                activitySign(obj.sid)
            }
        }
        //模拟数据
        /*if (pendingAdapter.itemCount == 0) {
            var lists: MutableList<String> = mutableListOf("","")
            mdatalist.addAll(lists)
            pendingAdapter.notifyDataSetChanged()
        }*/
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 301 && resultCode == Activity.RESULT_OK) {
            getDataList()
        }
    }

    //签到
    private fun activitySign(sid: String) {
        Alert.loading(self)
        ApiClient.api.activitySignIn(UserCache.token, sid, courseId)
            .compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    ShowToast("签到成功")
                    getDataList()

                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)

                }
            }
    }


    private var className = ""
    private var classTime = ""
    private var endtime = ""
    private var address=""
    private var latitude=""
    private var longitude=""

    private val dataList: MutableList<Studentlist> = mutableListOf()
    private fun getDataList() {
        Alert.loading(this)
        ApiClient.api.getDetailCourse(courseId, UserCache.token)
            .compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    stopRefresh()
                    topbar.apply {
                        setTitleBackColor(color(R.color.white))
                        setTitle(it.name)
                        setOnTopBarClickListener { obj, pos ->
                            if (pos == TopBar.Pos.LEFT) {
                                finish()
                            }
                        }
                    }
                    CLog.e("@@@=" + it.name)
                    address=it.address
                    latitude=it.latitude
                    longitude=it.longitude
                    /* if (classAdapter.itemCount == 0) {
                         var lists: MutableList<String> = mutableListOf("","")
                         mSourceList.addAll(lists)
                         classAdapter.notifyDataSetChanged()
                     }*/
                    //1未编辑，2已编辑，3已发布
                    if (it.status == "1") {
                        tv_know.text = "未编辑"
                    } else if (it.status == "2") {
                        tv_know.text = "已编辑"
                    } else if (it.status == "3") {
                        tv_know.text = "已发布"
                    }

                    className = it.name
                    classTime = it.startTime + "---" + it.endTime
                    tv_time.text = it.startTime + "---" + it.endTime
                    tv_address.text = it.address
                    dataList.clear()
                    if (curPage == 1) {
                        dataList.clear()
                        if (it.studentlist.size == 0) {
                            multiView.showEmpty()
                        }
                    }
                    if (it.studentlist.size <= 0) {
                        smartLayout.setEnableLoadMore(false)
                    } else {
                        curPage++
                        dataList.addAll(it.studentlist)
                        pendingAdapter.notifyDataSetChanged()
                        multiView.showContent()
                    }


                }
                _onError {
                    Alert.close()
                    stopRefresh()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }
    }


    private fun stopRefresh() {
        if (smartLayout.state == RefreshState.Refreshing) {
            smartLayout.finishRefresh()
        } else if (smartLayout.state == RefreshState.Loading) {
            smartLayout.finishLoadMore(100)
        }
    }

    private fun noticeRead(tid: String, remark: String, flag: Int) {
        // flag1.同意 2.拒绝
        ApiClient.api.approvalDeal(
            UserCache.token, tid, remark, flag.toString()
        ).compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    ShowToast("操作成功")
//                    presenter.getList(curPage, 0)
                    Alert.close()
                }
                _onError {
                    //                        Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }
    }


    override fun closeMvp() {
    }

}
